package network;

import jdk.nashorn.internal.runtime.Scope;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

public class UDPClient {
    private DatagramSocket socket=null;
    private String ServerIP;
    private int ServerPort;
    public UDPClient(String serverIP,int serverPort) throws SocketException {
        this.ServerIP= serverIP;
        this.ServerPort=serverPort;
        socket=new DatagramSocket();
    }

    public void start() throws IOException {
        System.out.println("客户端启动");
        Scanner sc=new Scanner(System.in);
        while (true){
            System.out.println("->");
            if (!sc.hasNext()){
                break;
            }
            String request=sc.next();
            DatagramPacket requestPacket=new DatagramPacket(request.getBytes(),request.getBytes().length,
                    InetAddress.getByName(ServerIP),ServerPort);
            //来自哪里的信息
            socket.send(requestPacket);
            // 4. 读取服务器的响应.
            DatagramPacket respondPacket=new DatagramPacket(new byte[1024],1024);
            socket.receive(respondPacket);

            String respond=new String(respondPacket.getData(),0,respondPacket.getLength());

            System.out.println(respond);
        }
    }

    public static void main(String[] args) throws IOException {
        UDPClient udpClient=new UDPClient("127.0.190.111", 9090);
        udpClient.start();
    }
}
